namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
	/// <summary>
	/// 1. Starts at Sales homepage
	/// 2. Click on Leads
	/// 3. Select Open Leads view
	/// 4. Add random string of two characters in look for textbox and click find
	/// 5. Double click a lead
	/// 6. Select Assign from Actions menu
	/// 7. Select Assign to another user radio button
	/// 8. Select a user from the search menu
	/// 9. Click OK
	/// 10. Click Save & Close
	/// </summary>
    
    public class AssignLead : CrmWebTest
    {
        public void AssignLead_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();

            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }
            
			EntityRequest LeadEr = new EntityRequest();
			LeadEr.Type = EntityNames.Leads;
			LeadEr.ParentID = Guid.NewGuid();
			LeadEr.ReturnAs = EntityNames.Leads;

			Props.Add(EntityNames.Accounts, new EntityRequest[] { LeadEr });

			er.Props = Props;

			System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			lead = (CRMEntity)Entities[EntityNames.Leads];

            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];
            
            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);
            
            user2 = EntityManager.Instance.GetNextUser(new Guid(user["organizationid"]));            
        }
        
        public void AssignLead_PostWebTest(object sender, PostWebTestEventArgs e)
        {            
            try
            {
                if (success)
                {
                    string newLeadId = lead[EntityIDNames.Lead];
                    if (newLeadId != null)
                    {
                        Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user2[EntityIDNames.User]), new Guid(user2["OrganizationId"]));
                        EntityManager.Instance.AddEntity(EntityNames.Leads, g, new string[] { "OwningUser", "LeadID", "FirstName", "LastName", "EntityManagerOwningUser" }, new string[] { user2["systemuserid"], lead[EntityIDNames.Lead], lead["firstname"], lead["lastname"], g.ToString() });
                    }
                }
            }
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Failed to convert bogus data into Guid. " + fe.ToString());
            }
            finally
            {
                EntityManager.Instance.FreeEntity(user);
                EntityManager.Instance.FreeEntity(user2);
                EntityManager.Instance.DeleteEntity(lead);
            }   
        }

        private void AssignLead_ValidateResponse(object sender, ValidationEventArgs e)
        {
            if (e.Response.StatusCode == HttpStatusCode.OK)
            {
                e.IsValid = true;
                success = true;
            }
            else
            {
                e.IsValid = false;
                success = false;
            }
        }

        public AssignLead()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());
            string random = Utils.GetRandomString(2, 2);
            gridXml = GridXmlHelper.LeadPageView(-1, openLeadsView, null);
            gridXml2 = GridXmlHelper.LeadSearchView(-1, searchLeadsView, random, null);
            gridRefreshXml = GridXmlHelper.LeadPageSearchViewRefresh(-1, searchLeadsView, random, null);

            this.Proxy = null;            
            PreWebTest += new EventHandler<PreWebTestEventArgs>(AssignLead_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(AssignLead_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            AppGridWebService.AppGridWebService ag;
            WebTestRequest wtr;

			this.BeginTransaction("NavLeadHomepage");

            // Get the home page
            _root_homepage_aspx hp = new _root_homepage_aspx(user);
            hp.etc = 4;
            yield return (hp);

			this.EndTransaction("NavLeadHomepage");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavOpenLeads");

                
                ag = new AppGridWebService.AppGridWebService();
                wtr = null;

                try { ag.Reset(gridXml, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavOpenLeads");
            }

			this.BeginTransaction("SearchLeads");

            // Search for the lead name
			ag = new AppGridWebService.AppGridWebService();
			wtr = null;

			try { ag.Reset(gridXml2, gridId); }
			catch (crmException x)
			{
				wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
			}
			yield return (wtr);

			this.EndTransaction("SearchLeads");

            this.BeginTransaction("OpenLead");

            // simulate double clicking of lead
            sfa_leads_edit_aspx dp = new sfa_leads_edit_aspx(user);
            dp.id = lead["leadid"];
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.ToString();

            _forms_FormScript_js_aspx fs = new _forms_FormScript_js_aspx(user);
            fs.etc = 1;
            fs.FormType = "main";
            fs.FormName = "crmForm";
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "referer";
            headerItem.Value = referer;
            fs.Headers.Add(headerItem);
            yield return (fs);
            
            this.EndTransaction("OpenLead");
            
            this.BeginTransaction("AssignLead");

            _grid_cmds_dlg_frmassign_aspx af = new _grid_cmds_dlg_frmassign_aspx(user);
            af.pId = new Guid(lead["leadid"]);
            af.pType = 4;
            af.iObjtype = 4;
            af.iTotal = 1;
            yield return (af);

            _controls_lookup_lookupsingle_aspx ls = new _controls_lookup_lookupsingle_aspx(user);
			ls.Class = "BasicOwner";
			ls.objecttypes = "8";
			ls.browse = 0;
            ls.ShowNewButton = 1;
            ls.ShowPropButton = 1;
			ls.DefaultType = 0;
			yield return (ls);
            
            // lead update form
            dp = new sfa_leads_edit_aspx(user);
            dp.crmFormSubmitXml ="<lead></lead>";

            dp.crmFormSubmitMode = 47;
            dp.crmFormSubmitObjectType = 4;
            dp.crmFormSubmitSecurity = 852023;
            dp.crmFormSubmitOnline = 1;
            dp.crmFormSubmitId = lead["leadid"];
            dp.id = lead["leadid"];
            dp.assignOwnerId = new Guid(user2["systemuserid"]);
            dp.assignOwnerType = 8;

            rpcInfo = Utils.GenerateWRPCToken(sfa_leads_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            dp.ValidateResponse += this.AssignLead_ValidateResponse;
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.ToString();

            fs = new _forms_FormScript_js_aspx(user);
            fs.etc = 1;
            fs.FormType = "main";
            fs.FormName = "crmForm";
            headerItem = new WebTestRequestHeader();
            headerItem.Name = "referer";
            headerItem.Value = referer;
            fs.Headers.Add(headerItem);
            yield return (fs);

            ag = new AppGridWebService.AppGridWebService();
            wtr = null;

            try { ag.Refresh(gridRefreshXml); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("AssignLead");
        }

        private string gridXml;
        private string gridXml2;
        private string gridRefreshXml;
        private static string gridId = "crmGrid";
        bool success;

        private CRMEntity user;
        private CRMEntity user2;
        private CRMEntity lead;
        private string crmServer;
        private string tokenKey;
        private string referer;
		
		private static string openLeadsView = "00000000-0000-0000-00AA-000010001006";
		private static string searchLeadsView = "F1A7C4D9-F439-46DA-8B69-ECC133214695";

        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
    }
}